<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="user.name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="user.age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="user.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
      <button @click="addOrEditFn">添加/修改</button>
    </div>
    <div v-show="arr.length > 0">
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(obj, index) in arr" :key="index">
          <td>{{index + 1}}</td>
          <td>{{obj.name}}</td>
          <td>{{obj.age}}</td>
          <td>{{obj.sex}}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="editFn(obj, index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
 
<script>
export default {
  data(){
    return{
        editIndex: -1,
        user:{name:'',age:0,sex:''},
        arr:[
        {name: 'Tom', age: 19, sex: '男'},
        {name: 'Jerry', age: 18, sex: '女'}
        ]
    }
  },
  methods:{
    addOrEditFn(){  //添加或修改方法
      if(this.editIndex === -1){
        //这里不能直接添加this.user，例如：this.arr.push(this.user)，会报错，不信你试试
        this.arr.push({...this.user});
      }else{  //编辑
        this.$set(this.arr, this.editIndex, {...this.user})
        this.editIndex = -1;
      }
      this.user = {name: '', age: 0, sex: ''}
    },  
    editFn(obj, index){
      //这里也不能写this.user = obj
      this.user = {...obj};
      this.editIndex = index; //正在编辑的索引
    },
    delFn(index){
      this.arr.splice(index, 1);
    }
  }
}
</script>